#include "TcpServer.hpp"
#include <memory>
#include <unordered_map>
#include <fstream>

#define FILENAME "OnlineDict.txt"

static Response Calculator(const Request &req)
{
    Response resp(0, 0);
    switch (req._op)
    {
    case '+':
        resp._ret = req._x + req._y;
        break;
    case '-':
        resp._ret = req._x - req._y;
        break;
    case '*':
        resp._ret = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
            resp._code = 1; // 除零错误
        else
            resp._ret = req._x / req._y;
        break;
    case '%':
        if (req._y == 0)
            resp._code = 2; // 模零错误
        else
            resp._ret = req._x % req._y;
        break;
    default:
        resp._code = 3;
        break;
    }
    return resp;
}

void NetCal(Connection* conn, std::string& request)
{
    logMessage(DEBUG, "NetCal Been Called, Get Request: %s", request.c_str());
    // 1. 反序列化
    Request req;
    if(!req.Deserialized(request)) 
    {
        // 按道理来说,来到这里收到的一定是一个完整的报文
        // 但现在却反序列化失败,输出一下错误日志
        logMessage(ERROR, "Request Deserialized Error");
        return; 
    }
    // 2. 业务处理
    Response resp = Calculator(req);
    // 3. 序列化,构建应答
    std::string sendStr = resp.Serialize();
    sendStr = Encode(sendStr);
    // 4. 业务层不需要关心数据如何发送给客户端，只需要将序
    // 列化后的应答交给TcpServer,让它将应答发送给客户端
    conn->_outBuffer += sendStr;
    // 一旦开启对EPOLLOUT的关心,epoll会立即触发一次发送事件就绪
    // 如果后续保持对EPOLL的关心,TcpServer会一直进行发送
    conn->_ptr->EnableReadWrite(conn, true, true);
}

// 加载单词
void LoadWord(std::unordered_map<std::string, std::string>& m)
{
    std::ifstream ifs(FILENAME);
    std::string key, value;
    while(ifs >> key >> value)
    {
        m[key] = value;
    }
}

void OnlineDict(Connection* conn, std::string& request)
{
    static std::unordered_map<std::string, std::string> m;
    // 加载单词且只加载一次
    if(m.empty()) LoadWord(m);
    // 观察单词是否加载成功
    // for(auto& kv : m)
    // {
    //     std::cout << kv.first << ":" << kv.second << std::endl;
    // }
    logMessage(DEBUG, "NetCal Been Called, Get Request: %s", request.c_str());
    // request就是要查找的单词
    auto it = m.find(request);
    std::string sendStr;
    if(it == m.end())
        sendStr = request +  " Is Not Found";
    else
        sendStr = request + " Means " + m[request];
    
    sendStr = Encode(sendStr); // 添加分隔符

    conn->_outBuffer += sendStr;
    // 一旦开启对EPOLLOUT的关心,epoll会立即触发一次发送事件就绪
    // 如果后续保持堆EPOLL的关心,TcpServer会一直进行发送
    conn->_ptr->EnableReadWrite(conn, true, true);
}

int main()
{
    std::unique_ptr<TcpServer> svr(new TcpServer());
    svr->Dispacther(OnlineDict);
    
    return 0;
}